package com.civ.sensor.dht.util;

import com.pi4j.wiringpi.Gpio;

public class SensorThread extends Thread {

	private boolean running = false;
	private static int start = 1;
	private static int end = 0;
	private int flag = end;
	DHT11 dht = new DHT11();
	HttpClient4yeeLink httpClient = new HttpClient4yeeLink();
	@Override
	final public void run() {
		running = true;
		try {
			while (!Thread.interrupted()) {
				flag = start;
				threadBody();
			}
		} catch (InterruptedException e) {
			System.out.println("DHT_Sensor sensor thread exception, or exit!");
		} finally {
			if (running == false) {
				cleanUp();
				return;
			}
		}

	}

	protected void cleanUp() {
		System.out.println("DHT_Sensor sensor thread clean over!");

	}

	protected void threadBody() throws InterruptedException {

		int value;

		if (Gpio.wiringPiSetup() < 0)
			System.out.println("Start DHT_Sensor sensor thread!");

		while (flag == start) {
			value = dht.DHT11_Read();
			if (value == 0) {
				if(dht.getTemperature()>=30||dht.getHumidity()>=30){
					ControlGpio.gpio("setstate",ControlGpio.GPIO_RELAY1,"高电平");
					ControlGpio.gpio("setstate",ControlGpio.GPIO_RELAY2,"高电平");
					ControlGpio.gpio("setstate",ControlGpio.GPIO_RELAY3,"高电平");
					ControlGpio.gpio("setstate",ControlGpio.GPIO_RELAY4,"高电平");
				}else{
					ControlGpio.gpio("setstate",ControlGpio.GPIO_RELAY1,"低电平");
					ControlGpio.gpio("setstate",ControlGpio.GPIO_RELAY2,"低电平");
					ControlGpio.gpio("setstate",ControlGpio.GPIO_RELAY3,"低电平");
					ControlGpio.gpio("setstate",ControlGpio.GPIO_RELAY4,"低电平");
				}
				httpClient.execute(dht.getTemperature(),HttpClient4yeeLink.tdPoint);
				httpClient.execute(dht.getHumidity(),HttpClient4yeeLink.hdPoint);
				System.out
						.println("Temperature is ["
								.concat(dht.getTemperature() + "],")
								.concat("Humidity is [")
								.concat(dht.getHumidity() + "]."));
			} else if (value == 2) {
				System.out
						.println("Get DHT_Sensor sensor parameter error,please try again!");
			} else {
				//System.out.println("Connection to  DHT_Sensor sensor time out,please try again!");
				Gpio.delay(60*1000);
			}
		}

	}

	//注意：这个方法只能被调用方使用，而不能在本线程内部使用，因为方法中有join的调用，自身的调用会导致死锁  
	public void end() {
		running = false;
		flag=end;
		this.interrupt();

		try {
			//挂起调用方的线程，直到本线程执行完毕  
			this.join();
		} catch (InterruptedException e) {
			System.out.println("DHT_Sensor sensor thread end!");
			e.printStackTrace();
		}
	}

	public static void main(String[] args) throws InterruptedException {
		SensorThread st = new SensorThread();
		st.start();
		Thread.sleep(2);
		st.end();
	}
}